package com.proyecto.core.modelo.servicio;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import com.proyecto.core.modelo.excepciones.GeneralException;

public class ServicioTransaccion {
	
	private Transaction transaccion = null;
	private Session sesion = null;
	private SessionFactory sesionFactory = null;
	
	public Session iniciarTransaccion() throws GeneralException{
		
		try{
			sesion = sesionFactory.openSession();
			transaccion = sesion.beginTransaction();
		}catch (Exception e) {
			throw new GeneralException("error.persona.transaccion.iniciar");
		}
		
		return sesion;
	}
	
	public void finalizarTransaccion() throws GeneralException{
		try{
			transaccion.commit();
			sesion.flush();
			transaccion = null;
			sesion.close();
			sesion = null;
		}catch (Exception e) {
			throw new GeneralException("error.persona.transaccion.finalizar");
		}
		
	}
	
	public void reversarTransaccion(){
		try{
			transaccion.rollback();
		}catch (Exception e) {
			// TODO: handle exception
		}finally{
			transaccion = null;
			sesion.close();
			sesion = null;
		}
	}

	public SessionFactory getSesionFactory() {
		return sesionFactory;
	}

	public void setSesionFactory(SessionFactory sesionFactory) {
		this.sesionFactory = sesionFactory;
	}
	
}
